<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:c="livcos.org/ns/cosmos"
  xmlns:da="livcos.org/ns/cosmos/data-access"
  xmlns:idx="livcos.org/ns/index"
  xmlns:f="livcos.org/ns/xslt/function"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns="http://www.w3.org/1999/xhtml"
  exclude-result-prefixes="c da f xs idx">

  <xsl:import href="../style/base.xsl" />
  <xsl:import href="../style/web.xsl" />
	
	<xsl:param name="q"/>
	<xsl:param name="idx"/>
	
	<xsl:variable name="indexId">
		<xsl:value-of select="$idx"/>
		<xsl:if test="not($idx)">
			<xsl:variable name="_i" select="$jobObject/c:request/header/cookie/value[@name = 'search_index']"/>
			<xsl:value-of select="if (normalize-space($_i) != '') then $_i else '/livcos.org'"/>
		</xsl:if>
	</xsl:variable>

	<xsl:variable name="params" as="element()*">
		<xsl:variable name="thisId" select="f:extract-object-id(static-base-uri())"/>
		<xsl:choose>
			<xsl:when test="f:object-available($indexId, 'content')">
				<xsl:sequence select="doc($indexId)/*/idx:query/idx:results[@ref = $thisId]/*"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:sequence select="doc(resolve-uri('DomainIndex'))/*/idx:query/idx:results[@ref = $thisId]/*"/>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:variable>
	
	<xsl:template match="/">
    <html>
    	<head profile="http://a9.com/-/spec/opensearch/1.1/">
        <title>Search</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      	<meta name="to-root-path" content="{$toRootPath}"/>
      	<link href="{f:caller-uri(resolve-uri('../css/styles.css'))}" rel="stylesheet" type="text/css"/>
      	<link href="{f:caller-uri(resolve-uri('css/search.css'))}" rel="stylesheet" type="text/css"/>
      	<link rel="shortcut icon" href="{f:caller-uri('/favicon.ico')}"/>
      	<link rel="search" type="application/opensearchdescription+xml"
      		title="LivCos Search" href="{resolve-uri('openSearch.xml', $jobObject/c:request/url)}"/>
      	<script type="text/javascript" src="{f:caller-uri(resolve-uri('../doc/script/scripts.js'))}">
      		<xsl:comment> </xsl:comment></script>
      	<script>
      		scriptSupport.addInit(function(evn) {
	      		var index = Dom("_index");
	      		index.cookie = new Cookie("search_index");
	      		index.setRefAutoComplete("<xsl:value-of select="$indexId"/>");
      		<xsl:if test="not($indexId)">
      			index.element.value = index.cookie.getValue();
      		</xsl:if>
      		});
      		function rememberIndex() {
	      		var index = Dom("_index");
	      		var uri = index.element.value;
	      		// strip ending '/' (eg. from ref-auto-complete)
	      		if (uri.charAt(uri.length - 1) == '/') {
	      			uri = uri.substring(0, uri.length - 1);
	      			index.element.value = uri;
	      		}
	      		index.cookie.setValue(uri);
      		}
      		function openJob(url) {
	      		window.open(url, '_blank', 'resizable=1,alwaysRaised=1,height=400,width=600,centerscreen');
	      		rememberIndex();
      		}
      	</script>
      </head>
      <body>
      	<form action="search.html" method="GET">
      		<table cellspacing="0">
      			<tbody>
      				<tr>
      					<td>Index:</td>
      					<td>
									<div style="position: relative;">
										<input id="_index" name="idx" type="text" value="{$indexId}" size="80" autocomplete="off"/>
									</div>
      					</td>
								<td>
									<input value="Update" type="button" title="Update the index, create if not exisiting."
										onclick="openJob('indexer.job?def=' + this.form.elements['idx'].value)"/>
									<xsl:text> </xsl:text>
									<input value="Clear" type="button" title="Clear the index. It can be recreated with the next update or query."
										onclick="openJob('indexer.job?action=clear&amp;def=' + this.form.elements['idx'].value)"
									/>
									<xsl:text> </xsl:text>
									<input value="Close" type="button" title="Close the index files."
										onclick="openJob('indexer.job?action=close&amp;def=' + this.form.elements['idx'].value)"
									/>
								</td>
      				</tr>
      				<tr>
      					<td>Query:</td>
      					<td>
      						<input name="q" type="text" value="{$q}" size="80"/>
      					</td>
      					<td>
									<input value="Search" type="submit" onclick="rememberIndex()" />
      					</td>
      				</tr>
      			</tbody>
      		</table>
      	</form>
      	<xsl:if test="$q">
   				<xsl:apply-templates select="f:query($indexId, $q)/*"/>
      	</xsl:if>
      </body>
    </html>
	</xsl:template>
	
	<xsl:template match="results">
		<div class="count">
			<xsl:choose>
				<xsl:when test="@total-hits = 0">No object found.</xsl:when>
				<xsl:when test="@total-hits = 1">1 object found:</xsl:when>
				<xsl:when test="@total-hits &gt; 100">First 100 of <xsl:value-of select="@total-hits"/> objects:</xsl:when>
				<xsl:otherwise><xsl:value-of select="@total-hits"/> objects found:</xsl:otherwise>
			</xsl:choose>
			</div>
		<xsl:apply-templates select="hit"/>
	</xsl:template>
	
	<xsl:template match="hit">
		<xsl:variable name="obj">
			<xsl:call-template name="param">
				<xsl:with-param name="name" select="'obj'"/>
			</xsl:call-template>
		</xsl:variable>
		<div class="result">
			<div class="title">
				<xsl:variable name="view">
					<xsl:call-template name="param">
						<xsl:with-param name="name" select="'view'"/>
					</xsl:call-template>
				</xsl:variable>
				<a href="{f:caller-uri($view, $obj)}.html">
					<xsl:call-template name="param">
						<xsl:with-param name="name" select="'title'"/>
					</xsl:call-template>
				</a>
			</div>
			<div class="summary">
				<xsl:call-template name="param">
					<xsl:with-param name="name" select="'summary'"/>
				</xsl:call-template>
			</div>
			<div class="foot">
				<xsl:variable name="type">
					<xsl:call-template name="param">
						<xsl:with-param name="name" select="'type'"/>
					</xsl:call-template>
				</xsl:variable>
				<xsl:if test="$type != ''">
					<span class="type">
						<xsl:text>[</xsl:text>
						<a href="{f:caller-uri(concat('/livcos.org/web/data', $obj, '.html'))}" title="Open raw data...">
							<xsl:text>&lt;</xsl:text>
							<xsl:value-of select="$type"/>
							<xsl:text>&gt;</xsl:text>
						</a>
						<xsl:text>]</xsl:text>
					</span>
					<xsl:text> </xsl:text>
				</xsl:if>
				<xsl:call-template name="obj-query">
					<xsl:with-param name="obj" select="$obj"/>
				</xsl:call-template>
			</div>
		</div>
	</xsl:template>
	
	<xsl:template name="param">
		<xsl:param name="name"/>
		<xsl:variable name="p" select="$params[@name = $name]"/>
		<xsl:choose>
			<xsl:when test="$p/@value">
				<xsl:value-of select="$p/@value"/>
			</xsl:when>
			<xsl:when test="$p/@xpath">
				<xsl:value-of select="f:eval($p/@xpath, .)"/>
			</xsl:when>
			<xsl:when test="$p/@field and $p/idx:map">
				<xsl:variable name="v" select="*[local-name() = $p/@field]"/>
				<xsl:variable name="m" select="$p/idx:map[@key = $v]"/>
				<xsl:variable name="m0" select="$p/idx:map[not(@key)]"/>
				<xsl:value-of select="if ($m) then $m/@value else if ($m0) then $m0/@value else $v"/>
			</xsl:when>
			<xsl:when test="$p/@field">
				<xsl:value-of select="*[local-name() = $p/@field]"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="*[local-name() = $name]"/>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>
	
	<xsl:template name="obj-query">
		<xsl:param name="obj"/>
		<xsl:param name="suffix" select="''"/>
		<xsl:if test="$obj != ''">
			<span>
				<xsl:call-template name="obj-query">
					<xsl:with-param name="obj" select="f:substring-before-last($obj, '/')"/>
					<xsl:with-param name="suffix" select="'/*'"/>
				</xsl:call-template>
				<xsl:text>/</xsl:text>
				<xsl:variable name="ext" select="concat(' AND obj:', $obj, $suffix)"/>
				<xsl:variable name="qry"
					select="if (contains($q, ' AND obj:')) then replace($q, ' AND obj:[^ ]*', $ext) else concat($q, $ext)"/>
				<a href="search.html?index={$indexId}&amp;q={$qry}"
					onmouseover="Dom(parentNode).addStyleClass('hover')"
					onmouseout="Dom(parentNode).removeStyleClass('hover')"
					title="Search within '{$obj}{$suffix}'">
					<xsl:value-of select="f:substring-after-last($obj, '/')"/>
				</a>
			</span>
		</xsl:if>
	</xsl:template>
  
</xsl:stylesheet>
